package com.whz.governance.redislimiter.tool;

import com.google.common.collect.Maps;
import lombok.experimental.UtilityClass;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Map;

/**
 * redis lua脚本执行辅助类
 *
 * @author whz
 */
@UtilityClass
public class RedisScriptUtils {

    @SuppressWarnings("rawtype")
    private static final Map<String, DefaultRedisScript> CACHE = Maps.newConcurrentMap();

    @SuppressWarnings("unchecked")
    public <T> DefaultRedisScript<T> readRedisScript(final String fileName, final Class<T> returnType) {
        return CACHE.computeIfAbsent(fileName, key -> {
            DefaultRedisScript<T> redisScript = new DefaultRedisScript<>();
            redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(getPath(fileName))));
            redisScript.setResultType(returnType);
            redisScript.afterPropertiesSet();
            return redisScript;
        });
    }

    private static String getPath(String fileName) {
        return "META-INF/generic-lua/" + fileName;
    }
}